﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace SlamCms.Common
{
	public static class ControlExtensions
	{
		public static T FindLastControl<T>(this Control control) where T : class
		{
			T foundControl = null;

			if (control != null)
			{
				if (control is T)
				{
					foundControl = control as T;
				}

				if (foundControl == null)
				{
					for (int i = control.Controls.Count - 1; i >= 0; i--)
					{
						foundControl = FindControl<T>(control.Controls[i]);
						if (foundControl != null) break;
					}
				}
			}

			return foundControl;
		}

		public static T FindLastControl<T>(this Control control, string id) where T : class
		{
			T foundControl = null;

			if (control != null)
			{
				if ((control.ID == null ? control.UniqueID.Equals(id, StringComparison.Ordinal) : control.ID.Equals(id, StringComparison.Ordinal)) && control is T)
				{
					foundControl = control as T;
				}

				if (foundControl == null)
				{
					for (int i = control.Controls.Count - 1; i >= 0; i--)
					{	
						foundControl = FindControl<T>(control.Controls[i], id);
						if (foundControl != null) break;
					}
				}
			}

			return foundControl;
		}

		public static T FindControl<T>(this Control control) where T : class
		{
			T foundControl = null;

			if (control != null)
			{
				if (control is T)
				{
					foundControl = control as T;
				}

				if (foundControl == null)
				{
					foreach (Control childControl in control.Controls)
					{
						foundControl = FindControl<T>(childControl);
						if (foundControl != null) break;
					}
				}
			}

			return foundControl;
		}

		public static T FindControl<T>(this Control control, string id) where T : class
		{
			T foundControl = null;

			if (control != null)
			{
				if ((control.ID == null ? control.UniqueID.Equals(id, StringComparison.Ordinal) : control.ID.Equals(id, StringComparison.Ordinal)) && control is T)
				{
					foundControl = control as T;
				}

				if (foundControl == null)
				{
					foreach (Control childControl in control.Controls)
					{
						foundControl = FindControl<T>(childControl, id);
						if (foundControl != null) break;
					}
				}
			}

			return foundControl;
		}
	}
}
